/**
 *
 */
package org.jenkon.io.filter;

import java.io.File;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * {@link FileFilter} implementing class for filter {@link File} extensions.
 * 
 * @author Jens Konopka
 * 
 */
public class ExtensionFileFilter implements FileFilter, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1051765388793937323L;
	private final Set<String> extensions = new HashSet<String>();
	private final boolean caseSensitive;

	/**
	 * @param extensions delegating extensions
	 */
	public ExtensionFileFilter(final String... extensions) {
		this(true, extensions);
	}

	/**
	 * @param extensions delegating extensions
	 * @param caseSensitive Case Sensitive or not
	 */
	public ExtensionFileFilter(final boolean caseSensitive, final String... extensions) {
		this(caseSensitive, Arrays.asList(extensions));
	}

	/**
	 * @param extensions {@link List} with extensions
	 */
	public ExtensionFileFilter(final List<String> extensions) {
		this(true, extensions);
	}

	/**
	 * @param extensions list with extensions
	 * @param caseSensitive Case Sensitive or not
	 */
	public ExtensionFileFilter(final boolean caseSensitive, final List<String> extensions) {
		this.extensions.addAll(extensions);
		this.caseSensitive = caseSensitive;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.io.FileFilter#accept(java.io.File)
	 */
	public boolean accept(final File pathname) {
		for (final String extension : this.extensions) {
			if (caseSensitive) {
				if (endsWith(pathname.getName(), extension)) {
					return true;
				}
			} else {
				if (endsWith(pathname.getName().toLowerCase(), extension.toLowerCase())) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * @param pathname the {@link File} to check
	 * @param extension extension to check
	 * @return true if {@link File#getName()} ends with extension
	 */
	private boolean endsWith(final String pathname, final String extension) {
		return pathname.endsWith(extension);
	}

}
